import React, {Component} from "react";
import {observer, inject} from "mobx-react";
import {withRouter} from "react-router-dom";
import {Form, Browser, Upload} from "weaver-mobile-page";
import {Tools, Bubble, Button, List, DatePicker, Icon, InputItem, ActivityIndicator, Progress} from "weaver-mobile";
import {getUrlParams} from "../../util";
import {createForm, formShape} from "rc-form";
import * as API from "../../api"

const isIPhone = new RegExp("\\biPhone\\b|\\biPod\\b", "i").test(window.navigator.userAgent);
let moneyKeyboardWrapProps;
if (isIPhone) {
    moneyKeyboardWrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

const getLabel = Tools.getLabel;

@inject("formOperationsStore")
@withRouter
@observer
class FormOperations extends Component {
    static propTypes = {
        formShape: formShape,
    };

    componentDidMount() {
        this.Init(this.props);
    }

    Init = (props) => {
        const {location, formOperationsStore: {init}} = props;
        init(getUrlParams(location.search))
    };
    renderForm = () => {

        const {form, groupToggle, setFormFields, taskInfo, browser, resetStage, source, viewtype, setFiles} = this.props.formOperationsStore;
        const {conditioninfo, isInit} = form;
        const prefixCls = "wm-form";
        const groups = [];
        const computeTime = (date, time) => {
            let val = [date, time].join(" ")
            if (time === "") {
                val += "00:00"
            }
            if (date === "") {
                return ""
            }
            return val;
        }
        const formParams = form.formParams;
        const beginTime = computeTime(formParams.begindate, formParams.begintime);
        const endTime = computeTime(formParams.enddate, formParams.endtime);
        const actualBeginTime = computeTime(formParams.actualbegindate, formParams.actualbegintime);
        const actualEndTime = computeTime(formParams.actualenddate, formParams.actualendtime);
        const workday = formParams.workday;
        const realmandays = formParams.realmandays;
        const finish = formParams.finish;

        const getFields = (c) => {
            const fields = [];
            c.items.forEach((field) => {
                    if (field.conditionType === "PRJDATETIME") {
                        if (field.domkey[0] === "begindate") {
                            fields.push(<DatePicker
                                key={field.domkey.join("__")}
                                value={beginTime}
                                maxDate={endTime}
                                onChange={(v) => {
                                    setFormFields({begindate__begintime: {value: v.split(" ")}});
                                    this.workdayComputed(v.split(" "), "begin")
                                }}
                            >
                                <List.Item arrow="horizontal">{field.label}</List.Item>
                            </DatePicker>)
                        } else if (field.domkey[0] === "enddate") {
                            fields.push(<DatePicker
                                key={field.domkey.join("__")}
                                value={endTime}
                                minDate={beginTime}
                                onChange={(v) => {
                                    v = v.split(" ");
                                    if (taskInfo.maxSubTaskEndDate === "" || typeof (taskInfo.maxSubTaskEndDate) === "undefined") {
                                        setFormFields({enddate__endtime: {value: v}});
                                        this.workdayComputed(v, "end")
                                    } else {
                                        if (new Date(v[0]) < new Date(taskInfo.maxSubTaskEndDate)) {
                                            Bubble.error(getLabel("83887", "任务完成的最后时间小于其子任务完成的最后时间！"), 1);
                                            setFormFields({enddate__endtime: {value: [taskInfo.maxSubTaskEndDate, formParams.endtime]}});
                                            this.workdayComputed([taskInfo.maxSubTaskEndDate, formParams.endtime], "end")
                                        } else {
                                            setFormFields({enddate__endtime: {value: v}});
                                            this.workdayComputed(v, "end")
                                        }
                                    }
                                }}>
                                <List.Item arrow="horizontal">{field.label}</List.Item>
                            </DatePicker>)
                        } else if (field.domkey[0] === "actualbegindate") {
                            fields.push(<DatePicker
                                key={field.domkey.join("__")}
                                value={actualBeginTime}
                                maxDate={actualEndTime}
                                onChange={(v) => {
                                    setFormFields({actualbegindate__actualbegintime: {value: v.split(" ")}});
                                    this.onActualComputed(v.split(" "), "begin")
                                }}
                            >
                                <List.Item arrow="horizontal">{field.label}</List.Item>
                            </DatePicker>)
                        } else if (field.domkey[0] === "actualenddate") {
                            fields.push(<DatePicker
                                key={field.domkey.join("__")}
                                value={actualEndTime}
                                minDate={actualBeginTime}
                                onChange={(v) => {
                                    setFormFields({actualenddate__actualendtime: {value: v.split(" ")}});
                                    this.onActualComputed(v.split(" "), "end")
                                }}
                            >
                                <List.Item arrow="horizontal">{field.label}</List.Item>
                            </DatePicker>)
                        }
                    } else if (field.conditionType === "ATTACHEMENT") {
                        if (field.domkey[0] === "accessory") {
                            fields.push(<List className="proj-accessory-list" key={field.domkey.join("__")}>
                                <List.Item extra={
                                    <div className="proj-accessory-upload">
                                        <Upload
                                            datas={field.datas}
                                            onChange={(filesIDs, data) => {
                                                setFiles(filesIDs);
                                                setFormFields({accessory: {value: filesIDs.join(",")}})
                                            }}
                                            limitType={""}
                                            multiSelection={true}
                                            // onItemClick={this.onFilePreView}
                                        />
                                    </div>
                                }>{field.label}</List.Item>
                            </List>)
                        }
                    } else if (field.domkey[0] === "workday") {
                        fields.push(<InputItem
                            key={field.domkey.join("__")}
                            value={workday}
                            placeholder={field.label}
                            ref={el => this.inputRef = el}
                            onVirtualKeyboardConfirm={v => {
                                setFormFields({workday: {value: v}});
                                this.endDateComputed(v)
                            }}
                            clear
                            moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                            onChange={v => {
                                setFormFields({workday: {value: v.trim()}});
                                this.endDateComputed(v)
                            }}

                        >{field.label}</InputItem>)
                    } else if (field.domkey[0] === "realmandays") {
                        fields.push(<InputItem
                            key={field.domkey.join("__")}
                            value={realmandays}
                            placeholder={field.label}
                            ref={el => this.inputRef = el}
                            moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                            onChange={v => {
                                setFormFields({realmandays: {value: v.trim()}});
                                this.actualEndDateComputed()
                            }}
                        >{field.label}</InputItem>)


                    } else if (field.domkey[0] === "finish") {
                        if (field.viewAttr > 1) {
                            fields.push(<InputItem
                                key={field.domkey.join("__")}
                                value={finish}
                                placeholder={field.label}
                                ref={el => this.inputRef = el}
                                onVirtualKeyboardConfirm={v => {
                                    this.checkProgress(v)
                                }}
                                viewAttr={field.viewAttr}
                                clear
                                moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                                onChange={v => {
                                    this.checkProgress(v)
                                }}
                            >{field.label}</InputItem>)
                        } else {
                            fields.push(
                                <List className="task-progress-disabled" key={field.domkey.join("__")}>
                                    <List.Item extra={
                                        <div>
                                            <div className="proj-show-info">
                                                <div className="progress">
                                                    <Progress percent={field.value} position="normal"/>
                                                </div>
                                                <div aria-hidden="true"><span
                                                    className="progress-text">{field.value}%</span>
                                                </div>
                                            </div>
                                            <div className="task-progress-befSpan"
                                            >{field.befSpan}</div>
                                        </div>
                                    }>{field.label}</List.Item>
                                </List>)
                        }

                    } else if (field.domkey[0] === "parentid" && source !== "task_child_task" && viewtype === "add") {
                        fields.push(<div
                            key={field.domkey.join("__")}
                            className="proj-form-browser-wrapper">
                            <div className="proj-form-browser-box">
                                <Browser
                                    label={getLabel("23785", "上级任务")}
                                    store={browser}
                                    hasAdvanceSerach
                                    isSingle={true}
                                    type={"prjtsk"}
                                    completeParams={field.browserConditionParam.completeParams}
                                    conditionDataParams={field.browserConditionParam.conditionDataParams}
                                    dataParams={field.browserConditionParam.dataParams}
                                    onChange={(...arg) => {
                                        const task = arg[2][0];
                                        if (task) {
                                            resetStage({viewAttr: 1}, task.id)
                                        } else {
                                            resetStage({viewAttr: 3})
                                        }
                                        setFormFields({"parentid": {value: [task]}})
                                    }}
                                />
                            </div>
                        </div>)
                    } else {
                        fields.push(<Form.Item
                            key={field.domkey.join("__")}
                            form={form}
                            fieldConfig={field}
                            onChange={form.onChange}
                        />);
                    }
                }
            )
            return fields;
        }
        if (isInit) {
            conditioninfo.forEach((c) => {
                groups.push(<div className={`${prefixCls}-group`} key={c.title}>
                        {c.title &&
                        <div className={`${prefixCls}-title`} onClick={() => groupToggle(c.title, !c.show)}>
                            {c.title}
                            <Icon type={c.show ? "up" : "down"}/>
                        </div>}
                        <div className={`${prefixCls}-list-wrap ${c.show ? "show" : "hide"}`}>
                            <List className="prj-self-form prj-data-picker-edit-css-style">
                                {getFields(c)}
                            </List>
                        </div>
                    </div>
                )

            });
        }
        return groups;
    }
    workdayComputed = (arg, type) => {
        const {setFormFields, form, taskInfo: {passnoworktime, userid}} = this.props.formOperationsStore;
        const formParams = form.formParams || {};
        if (type === "begin") {
            if (arg[0] && formParams.enddate) {
                this.datediff(arg[0], formParams.enddate, arg[1] || "00:00", formParams.endtime || "23:59", userid, passnoworktime,
                    (iDays) => setFormFields({workday: {value: iDays}}))
            }
        } else {
            if (arg[0] && formParams.begindate) {
                this.datediff(formParams.begindate, arg[0], formParams.begintime || "00:00", arg[1] || "23:59", userid, passnoworktime,
                    (iDays) => setFormFields({workday: {value: iDays}}));
            }
        }
    }
    onActualComputed = (arg, type) => { //maxSubTaskEndDate
        const {setFormFields, form, taskInfo: {passnoworktime, userid}} = this.props.formOperationsStore;
        const formParams = form.formParams || {};
        if (type === "begin") {
            if (arg[0] && formParams.actualenddate) {
                this.datediff(arg[0], formParams.actualenddate, arg[1] || "00:00", formParams.actualendtime || "23:59", userid, passnoworktime,
                    (iDays) => setFormFields({realmandays: {value: iDays}}));
            }
        } else {
            if (arg[0] && formParams.actualbegindate) {
                this.datediff(formParams.actualbegindate, arg[0], formParams.actualbegintime || "00:00", arg[1] || "23:59", userid, passnoworktime,
                    (iDays) => setFormFields({realmandays: {value: iDays}}));
            }
        }

    }
    endDateComputed = () => {
        const {setFormFields, form, taskInfo: {passnoworktime, userid}} = this.props.formOperationsStore;
        const formParams = form.formParams || {};
        let b = typeof (formParams.begindate) === "undefined" ? "" : formParams.begindate;
        let e = typeof (formParams.enddate) === "undefined" ? "" : formParams.enddate;
        let w = typeof (formParams.workday) === "undefined" ? "" : formParams.workday;
        let bt = typeof (formParams.begintime) === "undefined" ? "" : formParams.begintime;
        let et = typeof (formParams.endtime) === "undefined" ? "" : formParams.endtime;
        let alldate = "";
        if (bt === "") {
            bt = "00:00";
        }
        if (et === "") {
            et = "23:59";
        }

        if (w === "" && b !== "" && e !== "") {
            setFormFields({enddate: {value: ""}})
        } else if (w !== "" && ((b !== "" && e !== "") || (b !== "" && e === ""))) {
            if (w > 0) {
                let tmpesp;
                if (passnoworktime !== "1") {
                    alldate = this.addDate(b, w, bt, false);
                    tmpesp = alldate.split(" ");
                    setFormFields({enddate__endtime: {value: [tmpesp[0], tmpesp[1]]}})
                } else {
                    const params = {
                        method: "getEndDate",
                        workLong: w,
                        begindate: b,
                        begintime: bt,
                        manager: userid,
                        opttype: "worklong"
                    }
                    API.getDateByWorkLongCmd(params).then(res => {
                        alldate = res.returnvalue.trim();
                        if(alldate == "error"){
                            Bubble.error(getLabel(84409, "一般工作时间未设置，请告知管理员！"));
                            setFormFields({ enddate__endtime: {value: []} });
                        }else{
                            tmpesp = alldate.split(" ");
                            setFormFields({enddate__endtime: {value: [tmpesp[0], tmpesp[1]]}})
                        }  
                    })
                }
            } else {
                setFormFields({workday: {value: ""}, enddate__endtime: {value: []}})
            }

        } else if (w !== "" && b === "" && e !== "") {
            if (w > 0) {
                let tmpbsp;
                if (passnoworktime !== "1") {
                    alldate = this.addDate(e, -(w), et, true);
                    tmpbsp = alldate.split(" ");
                    setFormFields({begindate__begintime: {value: [tmpbsp[0], tmpbsp[1]]}})
                } else {
                    const params = {
                        method: "getBeginDate",
                        workLong: w,
                        enddate: e,
                        endtime: et,
                        manager: userid,
                        opttype: "worklong"
                    }
                    API.getDateByWorkLongCmd(params).then(res => {
                        alldate = res.returnvalue.trim();
                        if(alldate == "error"){
                            Bubble.error(getLabel(84409, "一般工作时间未设置，请告知管理员！"));
                            setFormFields({ enddate__endtime: {value: []} });
                        }else{
                            tmpbsp = alldate.split(" ");
                            setFormFields({enddate__endtime: {value: [tmpbsp[0], tmpbsp[1]]}})
                        }
                    })
                }
            } else {
                setFormFields({workday: {value: ""}, begindate__begintime: {value: []}})
            }
        }
    }

    actualEndDateComputed = () => {
        const {setFormFields, form, taskInfo: {passnoworktime, userid}} = this.props.formOperationsStore;
        const formParams = form.formParams || {};
        let b = typeof (formParams.actualbegindate) === "undefined" ? "" : formParams.actualbegindate;
        let e = typeof (formParams.actualenddate) === "undefined" ? "" : formParams.actualenddate;
        let w = typeof (formParams.realmandays) === "undefined" ? "" : formParams.realmandays;
        let bt = typeof (formParams.actualbegintime) === "undefined" ? "" : formParams.actualbegintime;
        let et = typeof (formParams.actualendtime) === "undefined" ? "" : formParams.actualendtime;
        let alldate = "";
        if (bt === "") {
            bt = "00:00";
        }
        if (et === "") {
            et = "23:59";
        }
        if (w === "" && b !== "" && e !== "") {
            setFormFields({actualenddate: {value: ""}})
        } else if (w !== "" && ((b !== "" && e !== "") || (b !== "" && e === ""))) {
            if (w > 0) {
                let tmpesp;
                if (passnoworktime !== "1") {
                    alldate = this.addDate(b, w, bt, false);
                    tmpesp = alldate.split(" ");
                    setFormFields({actualenddate__actualendtime: {value: [tmpesp[0], tmpesp[1]]}})
                } else {
                    const params = {
                        method: "getEndDate",
                        workLong: w,
                        begindate: b,
                        begintime: bt,
                        manager: userid,
                        opttype: "worklong"
                    }
                    API.getDateByWorkLongCmd(params).then(res => {
                        alldate = res.returnvalue.trim();
                        tmpesp = alldate.split(" ");
                        setFormFields({actualenddate__actualendtime: {value: [tmpesp[0], tmpesp[1]]}})
                    })
                }
            } else {
                setFormFields({realmandays: {value: ""}, actualenddate__actualendtime: {value: []}})
            }

        } else if (w !== "" && b === "" && e !== "") {
            if (w > 0) {
                let tmpbsp;
                if (passnoworktime !== "1") {
                    alldate = this.addDate(e, -(w), et, true);
                    tmpbsp = alldate.split(" ");
                    setFormFields({actualbegindate_actualbegintime: {value: [tmpbsp[0], tmpbsp[1]]}})
                } else {
                    const params = {
                        method: "getBeginDate",
                        workLong: w,
                        enddate: e,
                        endtime: et,
                        manager: userid,
                        opttype: "worklong"
                    }
                    API.getDateByWorkLongCmd(params).then(res => {
                        alldate = res.returnvalue.trim();
                        tmpbsp = alldate.split(" ");
                        setFormFields({actualbegindate_actualbegintime: {value: [tmpbsp[0], tmpbsp[1]]}})
                    })
                }
            } else {
                setFormFields({realmandays: {value: ""}, actualbegindate_actualbegintime: {value: []}})
            }
        }
    }


    datediff = (sDate1, sDate2, sDate3, sDate4, manager, passnoworktime, callback) => {
        let aDate, oDate1, oDate2, iDays = 0, tdate, oDatetime1, oDatetime2;

        if (Number(passnoworktime) !== 1) {

            oDate1 = new Date(sDate1);
            oDate2 = new Date(sDate2);

            if (true || "" + oDate1.getFullYear() === "NaN") {
                aDate = sDate1.split("-")
                tdate = sDate3.split(":")
                oDate1 = new Date((aDate[1] + "-" + aDate[2] + "-" + aDate[0]).replace(/-/g, "/"))   //转换为12-18-2002格式
                oDatetime1 = new Date((aDate[1] + "-" + aDate[2] + "-" + aDate[0] + " " + tdate[0] + ":" + tdate[1]).replace(/-/g, "/"))

                aDate = sDate2.split("-")
                tdate = sDate4.split(":")
                oDate2 = new Date((aDate[1] + "-" + aDate[2] + "-" + aDate[0]).replace(/-/g, "/"))
                oDatetime2 = new Date((aDate[1] + "-" + aDate[2] + "-" + aDate[0] + " " + tdate[0] + ":" + tdate[1]).replace(/-/g, "/"))

            }
            if (oDate2 - oDate1 < 0) {
                iDays = -1 	//日期
            } else if (oDate2 - oDate1 === 0) {
                if (sDate4 < sDate3) {
                    iDays = -2 //时间
                } else {
                    iDays = (Math.abs(oDatetime1 - oDatetime2) / 1000 / 60 / 60 / 24).toFixed(2)
                }
            } else {
                iDays = (Math.abs(oDatetime1 - oDatetime2) / 1000 / 60 / 60 / 24).toFixed(2)
            }

            callback(iDays)
        } else {   //计算去掉不包含非工作日
            const params = {
                begindate: sDate1,
                begintime: sDate3,
                enddate: sDate2,
                endtime: sDate4,
                manager: manager,
                opttype: "days"
            }
            API.getDateByWorkLongCmd(params).then(res => {
                iDays = res.returnvalue;
                callback(iDays)
            })
        }


    }
    addDate = (dd, dadd, bt, plus) => {
        let arr = dd.split("-");
        let btt = bt.split(":");
        let a = new Date(arr[0], arr[1] - 1, arr[2], btt[0], btt[1]).valueOf();
        const temp = a + dadd * 24 * 60 * 60 * 1000;
        a = plus ? temp + 60 * 1000 : temp - 60 * 1000;
        a = new Date(a);
        return this.format(a);
    }
    format = (date) => {
        let o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(),    //day
            "h+": date.getHours(),   //hour
            "m+": date.getMinutes(), //minute
            "s+": date.getSeconds(), //second
            "q+": Math.floor((date.getMonth() + 3) / 3),  //quarter
            "S": date.getMilliseconds() //millisecond
        }
        let format = "yyyy-MM-dd hh:mm";
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length === 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }
    checkProgress = (value) => {  //进度编辑校验
        const {taskInfo: {finishmax}, setFormFields} = this.props.formOperationsStore;
        if (Number(finishmax) === 99) {
            if (value > 99) {
                Bubble.error(getLabel("500800", "该任务所必须的相关文档或者相关流程不存在，任务不能完成") + "100%。", 1);
                setFormFields({finish: {value: 99}});
            } else {
                setFormFields({finish: {value: value}});
            }
        } else {
            if (value > 100) {
                setFormFields({finish: {value: 100}});
            } else if (value < 0) {
                setFormFields({finish: {value: 0}});
            } else {
                setFormFields({finish: {value: value}});
            }
        }
    }

    render() {
        const {history, formOperationsStore: {saveCard, isLoading, Toasting}} = this.props;
        return (<div>
                {isLoading ?
                    (<div className='loading'><ActivityIndicator animating size='large'/></div>)
                    :
                    <div>
                        <div className="form-wrapper-with-btn">
                            <div className="form-wrapper">
                                <Form>
                                    {this.renderForm()}
                                </Form>
                            </div>
                        </div>
                        <div className="proj-button-group">
                            <Button type="ghost" className='proj-button-cancel' onClick={() => {
                                history.go(-1)
                            }}>{getLabel("31129", "取消")}</Button>
                            <Button type="primary" className='proj-button-apply' disabled={Toasting} onClick={() => {
                                saveCard(history)
                            }}>{getLabel("30986", "保存")}</Button>
                        </div>
                    </div>

                }
            </div>
        )
    }
}

export default createForm()(FormOperations);
